package reflect_test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author yuisama
 * @date 2022/05/29 16:50
 **/
public class Test {
    public static void main(String[] args) throws Exception{
//        // 1.获取Student类的class对象
//        Class<Student> cls1 = (Class<Student>) Class.forName("reflect_test.Student");
//        // 2.通过类名称.class获取class对象
//        Class<Student> cls2 = Student.class;
//        // 3.通过Student对象的getClass方法
//        Class<Student> cls3 = (Class<Student>) new Student().getClass();
//        System.out.println(cls1 == cls2);
//        System.out.println(cls1 == cls3);
        Class<Student> cls = Student.class;
//        // 获取所有public权限的构造方法
//        Constructor[] constructors = cls.getConstructors();
//        for (Constructor constructor : constructors) {
//            System.out.println(constructor);
//        }
//        System.out.println("------------------------------");
//        // 获取该类所有构造方法
//        Constructor[] constructors1 = cls.getDeclaredConstructors();
//        for (Constructor constructor : constructors1) {
//            System.out.println(constructor);
//        }
        // 获取指定类型的有参构造
//        Constructor<Student> constructor = cls.getDeclaredConstructor(String.class,String.class,int.class);
//        Student student = constructor.newInstance("鹏哥","男",18);
//        System.out.println(student);
//        Constructor<Student> constructor = cls.getDeclaredConstructor(String.class);
//        // 破坏封装,通过反射破坏private封装，调用私有构造方法
//        constructor.setAccessible(true);
//        Student student = constructor.newInstance("鹏哥");
//        System.out.println(student);
        // 2.获取要调用方法的Method对象
//        Method method1 = cls.getDeclaredMethod("test");
//        // test是静态方法，无需产生Student对象
//        method1.invoke(null);
//
//        Method method2 = cls.getDeclaredMethod("fun",String.class);
//        Student student = new Student("先平","男",18);
//        method2.invoke(student,"先平的电脑修好了~~~");
        // 2.获取要拿到的属性Field对象
        Field field = cls.getDeclaredField("country");
        System.out.println(field.get(null));
        Field field1 = cls.getDeclaredField("age");
        Student student = new Student("先平","男",18);
        System.out.println(field1.get(student));
        field1.set(student,20);
        System.out.println(field1.get(student));
    }
}